// 全局变量
let metricsModal;

// 页面加载时初始化
window.onload = function() {
    // 初始化模态框
    metricsModal = new bootstrap.Modal(document.getElementById('metricsModal'));
    
    // 加载所有数据
    refreshAll();
    
    // 设置定时刷新（每30秒）
    setInterval(refreshAll, 30000);
};

// 刷新所有数据
function refreshAll() {
    getServiceList();
    getMetrics();
}

// 获取服务列表
function getServiceList() {
    fetch('/api/service/list')
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            if (result.code === 200) {
                displayServices(result.data || []);
            } else {
                throw new Error(result.message || '获取服务列表失败');
            }
        })
        .catch(error => {
             console.error('Error:', error);
             document.getElementById('serviceList').innerHTML = 
                 `<div class="alert alert-danger">
                     <i class="bi bi-exclamation-triangle"></i> 获取服务列表失败: ${error.message}
                 </div>`;
         });
}

// 显示服务列表
 function displayServices(services) {
     const serviceDiv = document.getElementById('serviceList');
     const serviceCountBadge = document.getElementById('serviceCount');
    
    serviceCountBadge.textContent = services.length;
    
    if (!services || services.length === 0) {
        serviceDiv.innerHTML = 
            `<div class="alert alert-info text-center">
                <i class="bi bi-info-circle fs-1 text-info"></i>
                <h5 class="mt-2">暂无注册的服务</h5>
                <p class="text-muted">请先注册服务实例</p>
            </div>`;
        return;
    }

    let html = '<div class="row">';
    services.forEach((service, index) => {
        const name = service.name;
        html += `
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="card h-100 shadow-sm">
                    <div class="card-body d-flex flex-column">
                        <div class="d-flex align-items-center mb-3">
                            <i class="bi bi-server fs-4 text-primary me-2"></i>
                            <h5 class="card-title mb-0">${name}</h5>
                        </div>
                        <div class="mt-auto">
                            <div class="d-grid gap-2">
                                <a href="/instance?serviceName=${name}" class="btn btn-primary">
                                    <i class="bi bi-eye"></i> 查看实例
                                </a>
                                <button class="btn btn-outline-secondary btn-sm" onclick="getInstanceCount('${name}', ${index})">
                                    <i class="bi bi-diagram-3"></i> 
                                    <span id="instanceCount_${index}">加载中...</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    html += '</div>';
    serviceDiv.innerHTML = html;
    
    // 异步加载每个服务的实例数量
    services.forEach((service, index) => {
        getInstanceCount(service.name, index);
    });
}

// 获取指定服务的实例数量
function getInstanceCount(serviceName, index) {
    fetch(`/api/instance/list?serviceName=${serviceName}`)
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                const instances = result.data || [];
                const healthyCount = instances.filter(inst => inst.weight > 0).length;
                const totalCount = instances.length;
                
                const countElement = document.getElementById(`instanceCount_${index}`);
                if (countElement) {
                    countElement.innerHTML = `${healthyCount}/${totalCount} 健康`;
                    countElement.className = healthyCount === totalCount ? 'text-success' : 'text-warning';
                }
            }
        })
        .catch(error => {
            console.error('Error getting instance count:', error);
            const countElement = document.getElementById(`instanceCount_${index}`);
            if (countElement) {
                countElement.innerHTML = '获取失败';
                countElement.className = 'text-danger';
            }
        });
}

// 获取系统指标
function getMetrics() {
    fetch('/metrics')
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                updateMetricsDisplay(result.data);
            }
        })
        .catch(error => {
            console.error('Error getting metrics:', error);
        });
}

// 更新指标显示
function updateMetricsDisplay(metrics) {
    // 更新概览卡片
    document.getElementById('totalServices').textContent = metrics.total_services || 0;
    document.getElementById('totalInstances').textContent = metrics.total_instances || 0;
    document.getElementById('healthyInstances').textContent = metrics.healthy_instances || 0;
    document.getElementById('uptime').textContent = metrics.uptime || '-';
}

// 显示监控模态框
function showMetrics() {
    // 获取详细指标
    fetch('/status')
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                displayDetailedMetrics(result.data);
            }
        })
        .catch(error => {
            console.error('Error getting detailed metrics:', error);
            document.getElementById('metricsContent').innerHTML = 
                `<div class="alert alert-danger">获取监控数据失败: ${error.message}</div>`;
        });
    
    metricsModal.show();
}

// 显示详细指标
function displayDetailedMetrics(data) {
    const metrics = data.metrics;
    const components = data.components;
    
    const html = `
        <div class="row">
            <div class="col-md-6">
                <h6><i class="bi bi-graph-up"></i> 请求统计</h6>
                <table class="table table-sm">
                    <tr><td>总请求数</td><td class="text-end">${metrics.total_requests}</td></tr>
                    <tr><td>心跳请求</td><td class="text-end">${metrics.heartbeat_requests}</td></tr>
                    <tr><td>API请求</td><td class="text-end">${metrics.api_requests}</td></tr>
                </table>
                
                <h6><i class="bi bi-server"></i> 服务统计</h6>
                <table class="table table-sm">
                    <tr><td>服务总数</td><td class="text-end">${metrics.total_services}</td></tr>
                    <tr><td>实例总数</td><td class="text-end">${metrics.total_instances}</td></tr>
                    <tr><td>健康实例</td><td class="text-end text-success">${metrics.healthy_instances}</td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6><i class="bi bi-cpu"></i> 系统信息</h6>
                <table class="table table-sm">
                    <tr><td>运行时间</td><td class="text-end">${metrics.uptime}</td></tr>
                    <tr><td>内存使用</td><td class="text-end">${metrics.memory_usage}</td></tr>
                    <tr><td>协程数量</td><td class="text-end">${metrics.goroutines}</td></tr>
                    <tr><td>GC次数</td><td class="text-end">${metrics.gc_count}</td></tr>
                </table>
                
                <h6><i class="bi bi-check-circle"></i> 组件状态</h6>
                <table class="table table-sm">
    `;
    
    let componentRows = '';
    for (const [component, status] of Object.entries(components)) {
        const statusClass = status === 'healthy' ? 'text-success' : 'text-danger';
        const statusIcon = status === 'healthy' ? 'bi-check-circle' : 'bi-x-circle';
        componentRows += `<tr><td>${component}</td><td class="text-end ${statusClass}"><i class="bi ${statusIcon}"></i> ${status}</td></tr>`;
    }

    document.getElementById('metricsContent').innerHTML = html + componentRows + `
                </table>
            </div>
        </div>
        <div class="row mt-3">
            <div class="col-12">
                <small class="text-muted">
                    <i class="bi bi-clock"></i> 最后更新: ${new Date(data.timestamp).toLocaleString()}
                </small>
            </div>
        </div>
    `;
}
